import React, { useState, useEffect, useMemo } from 'react';
import styles from "./index.module.less";
import { useTableContext } from '../context';
import { SettingOutlined, MenuOutlined } from '@ant-design/icons';
import { Button, Popover, Checkbox, Space, Divider } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';

type Props = {
    show?: boolean;
}

// 排序项组件
const SortableItem = React.memo(({ column, checked, onCheck }: { 
  column: any; 
  checked: boolean;
  onCheck: (dataIndex: string, checked: boolean) => void;
}) => {
    // 使用dnd-kit的useSortable hook
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
    } = useSortable({ id: column.dataIndex });

    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
        marginBottom: '8px',
    };

    return (
        <div ref={setNodeRef} style={style} className={styles.columnItem}>
            <Space>
                <span className={styles.dragHandle} {...attributes} {...listeners}>
                    <MenuOutlined
                        style={{
                            color: '#999',
                            fontSize: '14px',
                            cursor: 'grab'
                        }}
                    />
                </span>
                <Checkbox
                    checked={checked}
                    onChange={(e) => onCheck(column.dataIndex as string, e.target.checked)}
                >
                    {typeof column.title === 'function' ? '列' : column.title}
                </Checkbox>
            </Space>
        </div>
    );
});

const Setting = React.memo((props: Props) => {
    const tableData = useTableContext();
    const settingColumns = useMemo(() => 
        tableData.columns.filter(item => item.dataIndex !== 'operation'), 
        [tableData.columns]
    );
    
    const [settingPopoverVisible, setSettingPopoverVisible] = useState<boolean>(false);
    const [checkedColumns, setCheckedColumns] = useState<string[]>([]);
    const [columnOrder, setColumnOrder] = useState<string[]>([]);

    // 配置拖拽传感器
    const sensors = useSensors(
        useSensor(PointerSensor),
        useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
    );

    useEffect(() => {
        const columnDataIndexes = settingColumns.map(col => col.dataIndex as string);
        setCheckedColumns(columnDataIndexes);
        setColumnOrder(columnDataIndexes);
    }, [JSON.stringify(settingColumns.map(col => col.dataIndex))]);

    useEffect(() => {
        applyColumnSettings();
    }, [checkedColumns, columnOrder])

    const handleCheckAll = (e: CheckboxChangeEvent) => {
        const newCheckedColumns = e.target.checked
            ? settingColumns.map(col => col.dataIndex as string)
            : [];
        setCheckedColumns(newCheckedColumns);
    };

    const handleCheck = (dataIndex: string, checked: boolean) => {
        const newCheckedColumns = checked
            ? [...checkedColumns, dataIndex]
            : checkedColumns.filter(item => item !== dataIndex);
        setCheckedColumns(newCheckedColumns);
    };

    const handleReset = () => {
        setCheckedColumns(settingColumns.map(col => col.dataIndex as string));
    };

    const isAllChecked = settingColumns.length === checkedColumns.length;

    const renderColumnSettings = () => (
        <div className={styles.columnSettingContent}>
            <div className={styles.settingHeader}>
                <Checkbox
                    checked={isAllChecked}
                    onChange={handleCheckAll}
                >
                    全选
                </Checkbox>
                <Button style={{ padding: 0 }} type="link" onClick={handleReset}>重置</Button>
            </div>

            <Divider style={{ margin: '8px 0' }} />

            <div className={styles.columnList}>
                <DndContext
                    sensors={sensors}
                    collisionDetection={closestCenter}
                    onDragEnd={handleDragEnd}
                >
                    <SortableContext
                        items={columnOrder}
                        strategy={verticalListSortingStrategy}
                    >
                        {columnOrder.map(dataIndex => {
                            const column = settingColumns.find(col => col.dataIndex === dataIndex);
                            if (!column) return null;
                            return (
                                <SortableItem 
                                    key={dataIndex} 
                                    column={column}
                                    checked={checkedColumns.includes(dataIndex)} 
                                    onCheck={handleCheck}
                                />
                            );
                        })}
                    </SortableContext>
                </DndContext>
            </div>
        </div>
    );

    const applyColumnSettings = () => {
        // 更新表格列的显示/隐藏状态和顺序
        const newColumns = [...tableData.columns];

        // 创建一个映射以便于重新排序
        const columnMap = new Map(newColumns.map(col => [col.dataIndex, col]));

        // 按照新的列顺序排序，但保留操作列在最后
        const orderedColumns = [];

        // 先添加按顺序排列的普通列
        for (const dataIndex of columnOrder) {
            if (columnMap.has(dataIndex)) {
                const col = columnMap.get(dataIndex);
                if (col) {
                    orderedColumns.push({
                        ...col,
                        hidden: !checkedColumns.includes(col.dataIndex as string)
                    });
                    columnMap.delete(dataIndex);
                }
            }
        }

        // 添加操作列和任何其他剩余的列
        columnMap.forEach(col => {
            orderedColumns.push({
                ...col,
                hidden: col.dataIndex !== 'operation' && !checkedColumns.includes(col.dataIndex as string)
            });
        });

        // 如果tableData有更新列的方法，则调用
        if (tableData.setColumns) {
            tableData.setColumns(orderedColumns);
        }
    };

    // 处理拖拽结束事件
    const handleDragEnd = (event: any) => {
        const { active, over } = event;

        if (active.id !== over?.id) {
            setColumnOrder((items) => {
                const oldIndex = items.indexOf(active.id);
                const newIndex = items.indexOf(over.id);
                return arrayMove(items, oldIndex, newIndex);
            });
        }
    };

    return (
        <div>
            {props.show &&
                <Popover
                    key="setting"
                    content={renderColumnSettings()}
                    title="列设置"
                    trigger="click"
                    open={settingPopoverVisible}
                    onOpenChange={setSettingPopoverVisible}
                    zIndex={1000}
                >
                    <Button icon={<SettingOutlined />}>
                        列设置
                    </Button>
                </Popover>
            }
        </div>
    );
});

export default Setting;